package aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 编写一个共享锁 加深理解
 * 
 * @author insight
 * @since 2021/9/13
 */
public class TwinsLock implements Lock {
    private static final Sync SYNC = new Sync(2);

    @Override
    public void lock() {
        SYNC.acquireShared(1);
    }

    @Override
    public void unlock() {
        SYNC.releaseShared(1);
    }

    /**
     * 其他方法没用到 就不重写了
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        SYNC.acquireSharedInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return SYNC.newCondition();
    }

    private static class Sync extends AbstractQueuedSynchronizer {
        Sync(int count) {
            setState(count);
        }
        
        /**
         * 通过死循环和 CAS 来获取锁
         */
        @Override
        protected int tryAcquireShared(int reduce) {
            for (; ; ) {
                int curCnt = getState();
                int newCnt = curCnt - reduce;
                if (newCnt < 0 || compareAndSetState(curCnt, newCnt)) {
                    return newCnt;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int increase) {
            for (; ; ) {
                int curCnt = getState();
                int newCnt = curCnt + increase;
                if (compareAndSetState(curCnt, newCnt)) {
                    return true;
                }
            }
        }

        private Condition newCondition() {
            return new ConditionObject();
        }
    }
    
}